package com.hj.config;

import com.hj.dao.UserDao;
import com.hj.model.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author haoshen
 * @version 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("user");
        Cookie[] cookies = request.getCookies();
        //session中有user  直接放行
        if (user instanceof User) {
            return true;
        }
        //cookie中有用户信息 放行且将用户信息存入session
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("user".equals(cookie.getName())) {
                    User user1 = new User();
                    user1.setUsername(cookie.getValue());
                    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
                    UserDao userDao = (UserDao) factory.getBean("userDao");
                    User user2 = userDao.selectOne(user1);
                    request.getSession().setAttribute("user", user2);
                    return true;
                }
            }
        }

        response.sendRedirect("/index");
        return false;
    }
}
